import axios from 'axios';
import router from './router.js';

axios.defaults.baseURL = 'http://localhost:7000/'
axios.defaults.timeout = 3000
axios.defaults.headers = { 'Content-type': 'application/json; charset=UTF-8' }

axios.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem("token")
        if (token) {
            config.headers["Authorization"] = token
        }
        if (config.method == 'post' || config.method == 'put') {
            config.data = JSON.stringify(config.data)
        }
        return config
    },
    (err) => {
        return Promise.resolve(err)
    }
)

axios.interceptors.response.use(
    (response) => {
        if (!response || !response.data || !response.data.success) {
            console.log("test")
        }
        if (response) {
            console.log(response)
        }
        return response
    }, (err) => {
        switch (err.response.data.statusCode) {
            case 401:
                alert("请先登录！, 即将跳转")
                setTimeout(() => {
                    router.replace({
                        path: '/login'
                    })
                }, 500)
                break
            case 403:
                setTimeout(() => {
                    router.replace({
                        path: '/forbidden'
                    })
                }, 500)
                break
            case 400:
                setTimeout(() => {
                    router.replace({
                        path: '/error'
                    })
                }, 500)
                break
            case 500:
                setTimeout(() => {
                    router.replace({
                        path: '/error'
                    })
                }, 500)
                break
        }
        return err
    }
)


  
